/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.masterdata.company.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.redragon.framework.springmvc.ControllerSupport;
import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.hibernate.model.TreeNode;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.JsonUtil;
import com.erp.masterdata.company.dao.model.MdFinanceCompany;
import com.erp.masterdata.company.dao.model.MdFinanceCompanyCO;
import com.erp.masterdata.company.service.MdFinanceCompanyService;
import com.erp.masterdata.subject.dao.model.MdFinanceSubjectDetail;
import com.erp.masterdata.subject.dao.model.MdFinanceSubjectDetailCO;

@Controller
@RequestMapping("/web/mdFinanceCompany")
public class MdFinanceCompanyWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(MdFinanceCompanyWebController.class);
    
    //服务层注入
    @Autowired
    private MdFinanceCompanyService mdFinanceCompanyService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getMdFinanceCompanyList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2021-01-22 22:53:28
     * @author 
     * @param pages
     * @param mdFinanceCompanyCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getMdFinanceCompanyList")
    public String getMdFinanceCompanyList(Pages pages, MdFinanceCompanyCO mdFinanceCompanyCO, Model model) {
        return "basic.jsp?content=mdCompany/companyList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2021-01-22 22:53:28
     * @author 
     * @param mdFinanceCompany
     * @param model
     * @return String
     *
     */
    @RequestMapping("getMdFinanceCompany")
    @ResponseBody
    public String getMdFinanceCompany(MdFinanceCompany mdFinanceCompany, Model model) {
        String companyCode = "";
        String companyName = "";
        String segmentCode = "";
        String segmentDesc = "";
        
        //查询要编辑的数据
        if(mdFinanceCompany!=null&&mdFinanceCompany.getCompanyId()!=null) {
            mdFinanceCompany = this.mdFinanceCompanyService.getDataObject(mdFinanceCompany.getCompanyId());
            companyCode = mdFinanceCompany.getCompanyCode();
            companyName = mdFinanceCompany.getCompanyName();
            segmentCode = mdFinanceCompany.getSegmentCode().substring(mdFinanceCompany.getSegmentCode().indexOf("_")+1);
            segmentDesc = mdFinanceCompany.getSegmentDesc().substring(mdFinanceCompany.getSegmentDesc().indexOf("_")+1);
        }
        
        return "{\"companyCode\":\""+companyCode+"\",\"companyName\":\""+companyName+"\",\"segmentCode\":\""+segmentCode+"\",\"segmentDesc\":\""+segmentDesc+"\"}";
    }
    
    
    
    /**
     * 
     * @description 获取科目树
     * @date 2020年7月5日
     * @author dongbin
     * @param model
     * @return String
     *
     */
    @RequestMapping("getMdFinanceCompanyTree")
    public String getMdFinanceCompanyTree(Model model) {
        model.addAttribute("treeType", "write");
        model.addAttribute("title", "公司结构（财务）");
        model.addAttribute("editNodeModalUrl", "web/mdFinanceCompany/getMdFinanceCompanyEditModal");
        model.addAttribute("getTreeDataUrl", "web/mdFinanceCompany/getMdFinanceCompanyTreeData");
        model.addAttribute("deleteNodeUrl", "web/mdFinanceCompany/deleteMdFinanceCompany?companyId=");
        
        return "common/tree/tree";
    }
    
    
    
    @RequestMapping("getMdFinanceCompanyTreeReadOnly")
    public String getMdFinanceCompanyTreeReadOnly(Model model) {
        model.addAttribute("treeType", "read");
        model.addAttribute("title", "公司结构（财务）");
        model.addAttribute("editNodeModalUrl", "web/mdFinanceCompany/getMdFinanceCompanyEditModal");
        model.addAttribute("getTreeDataUrl", "web/mdFinanceCompany/getMdFinanceCompanyTreeData");
        model.addAttribute("deleteNodeUrl", "web/mdFinanceCompany/deleteMdFinanceCompany?companyId=");
        
        return "common/tree/tree";
    }
    
    
    
    @RequestMapping(value="getMdFinanceCompanyTreeData", produces = "application/json")
    @ResponseBody
    public String getMdFinanceCompanyTreeData(String nodeId) {
        //获取公司列表
        List<MdFinanceCompany> list = this.mdFinanceCompanyService.getDataObjects(new MdFinanceCompanyCO());
        //根节点
        TreeNode rootNode = new TreeNode();
        //节点Map
        Map<String, TreeNode> treeNodeMap = new TreeMap<String, TreeNode>();
        
        //重组组织树
        for(int a=0;a<list.size();a++) {
            MdFinanceCompany obj = list.get(a);
            
            if(a==0) {
                //设置根节点
                rootNode.setId(obj.getCompanyId().toString());
                rootNode.setCode(obj.getCompanyCode());
                rootNode.setText(obj.getCompanyName()+(obj.getStatus().equals("N")?"(停用)":""));
                rootNode.setType("root");
                Map<String, Boolean> stateMap = new HashMap<String, Boolean>();
                stateMap.put("opened", true);
                rootNode.setState(stateMap);
                rootNode.setChildren(this.getAllChildrenNode(obj, list, treeNodeMap));
                //设置节点Map
                treeNodeMap.put(obj.getCompanyCode(), rootNode);
            }else {
                //设置其他节点
                if(treeNodeMap.containsKey(obj.getCompanyCode())) {
                    TreeNode node = treeNodeMap.get(obj.getCompanyCode());
                    node.setChildren(this.getAllChildrenNode(obj, list, treeNodeMap));
                }else {
                    TreeNode node = new TreeNode();
                    node.setId(obj.getCompanyId().toString());
                    node.setCode(obj.getCompanyCode());
                    node.setText(obj.getCompanyCode()+" "+obj.getCompanyName()+(obj.getStatus().equals("N")?"(停用)":""));
                    node.setType("node");
                    node.setChildren(this.getAllChildrenNode(obj, list, treeNodeMap));
                    //设置节点Map
                    treeNodeMap.put(obj.getCompanyCode(), node);
                }
            }
        }
        
        return JsonUtil.objectToJson(rootNode);
    }
    
    //返回所有直接子节点
    private List<TreeNode> getAllChildrenNode(MdFinanceCompany currentObj, List<MdFinanceCompany> list, Map<String, TreeNode> treeNodeMap) {
        List<TreeNode> childrenNodeList = new ArrayList<TreeNode>();
        //获取父节点段值数量
        int segmentNum = currentObj.getSegmentCode().split("_").length;
        
        for(MdFinanceCompany obj: list) {
            //获取节点段值数量
            int segmentNumTemp = obj.getSegmentCode().split("_").length;
            //判断父节点的直接子节点
            if(segmentNumTemp==segmentNum+1&&obj.getSegmentCode().contains(currentObj.getSegmentCode())) {
                if(treeNodeMap.containsKey(obj.getCompanyCode())) {
                    TreeNode node = treeNodeMap.get(obj.getCompanyCode());
                    childrenNodeList.add(node);
                }else {
                    TreeNode node = new TreeNode();
                    node.setId(obj.getCompanyId().toString());
                    node.setCode(obj.getCompanyCode());
                    node.setText(obj.getCompanyCode()+" "+obj.getCompanyName()+(obj.getStatus().equals("N")?"(停用)":""));
                    node.setType("node");
                    childrenNodeList.add(node);
                    //设置节点Map
                    treeNodeMap.put(obj.getCompanyCode(), node);
                }
            }
        }
        
        return childrenNodeList;
    }
    
    
    
    /**
     * 
     * @description 获取组织编辑模态对话框
     * @date 2020年7月5日
     * @author dongbin
     * @param nodeCode
     * @param model
     * @return String
     *
     */
    @RequestMapping("getMdFinanceCompanyEditModal")
    public String getMdFinanceCompanyEditModal(String nodeId, Model model) {
        
        //修改时获取当前节点
        if(StringUtils.isNotBlank(nodeId)) {
            MdFinanceCompany parentNode = this.mdFinanceCompanyService.getDataObject(Integer.parseInt(nodeId));
            model.addAttribute("nodeCodeValue", parentNode.getCompanyCode());
            model.addAttribute("nodeNameValue", parentNode.getCompanyName());
            model.addAttribute("nodeStatusValue", parentNode.getStatus());
            model.addAttribute("nodeCreatedDateValue", parentNode.getCreatedDate());
            model.addAttribute("nodeCreatedByValue", parentNode.getCreatedBy());
        }
       
        
        model.addAttribute("nodeId", "companyId");
        model.addAttribute("nodeCode", "companyCode");
        model.addAttribute("nodeName", "companyName");
        model.addAttribute("editNodeUrl", "web/mdFinanceCompany/editMdFinanceCompany");
        
        return "common/tree/editNodeModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2021-01-22 22:53:28
     * @author 
     * @param mdFinanceCompany
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editMdFinanceCompany")
    @ResponseBody
    public String editMdFinanceCompany(@Valid @RequestBody MdFinanceCompany obj, @RequestParam String parentId, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            //参数校验
            /*
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getHrDepartmentEditModal";
            }*/
            
            //判断是新增还是修改
            String editStatus = null;
            if(obj.getCompanyId()!=null) {
                editStatus = "update";
            }else {
                editStatus = "insert";
            }
            
            //对当前编辑的对象初始化默认的字段
            //根节点
            if(StringUtils.isBlank(parentId)) {
                editStatus = "addRoot";
                obj.setSegmentCode(obj.getCompanyCode());
                obj.setSegmentDesc(obj.getCompanyName());
            }else {
                //获取父节点
                MdFinanceCompany parentNode = this.mdFinanceCompanyService.getDataObject(Integer.parseInt(parentId));
                obj.setParentCompanyCode(parentNode.getCompanyCode());
                obj.setSegmentCode(parentNode.getSegmentCode()+"_"+obj.getCompanyCode());
                obj.setSegmentDesc(parentNode.getSegmentDesc()+"_"+obj.getCompanyName());
            }
            
            //保存编辑的数据
            this.mdFinanceCompanyService.insertOrUpdateDataObject(obj);
            
            //停用设置
            if(obj.getStatus().equals("N")) {
                obj.setCompanyName(obj.getCompanyName()+"(停用)");
            }
            
            return "{\"result\":\"success\",\"editStatus\":\""+editStatus+"\",\"nodeId\":\""+obj.getCompanyId()+"\",\"nodeText\":\""+obj.getCompanyName()+"\"}";
        }catch(Exception e) {
            
        }
        
        return "{\"result\":\"error\"}";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2021-01-22 22:53:28
     * @author 
     * @param mdFinanceCompany
     * @return String
     *
     */
    @RequestMapping("deleteMdFinanceCompany")
    @ResponseBody
    public String deleteMdFinanceCompany(MdFinanceCompany obj, RedirectAttributes attr) {
        //删除数据前验证数据
        if(obj!=null&&obj.getCompanyId()!=null) {
            int childNum = this.mdFinanceCompanyService.getChildNodeNum(obj.getCompanyId());
            if(childNum==0) {
                //删除数据
                this.mdFinanceCompanyService.deleteDataObject(obj);
                
                return "{\"result\":\"success\"}";
            }else {
                return "{\"result\":\"hint\",\"hintMessage\":\"当前节点存在子节点，不能删除\"}";
            }
            
        }
        
        return "{\"result\":\"error\"}";
    }
}
